package com.yswy.app.service.impl;

import com.alibaba.nacos.common.util.Md5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yswy.app.dto.TgCallBackIdReids;
import com.yswy.app.service.AppUserService;
import com.yswy.app.service.SysConfigService;
import com.yswy.app.service.TgCallBackKsIdService;
import com.yswy.app.service.TgChannleService;
import com.yswy.common.runnableUtil.Pooled;
import com.yswy.common.utils.HttpUtil;
import com.yswy.common.utils.StringUtils;
import com.yswy.common.utils.redis.RedisConstants;
import com.yswy.common.utils.redis.RedisUtil;
import com.yswy.domain.common.BasePojo;
import com.yswy.domain.entity.*;
import com.yswy.domain.mapper.TgBindCsjAdMapper;
import com.yswy.domain.mapper.TgCallBackKsIdMapper;
import com.yswy.domain.mapper.TgChannleChildMapper;
import com.yswy.domain.vo.dto.TgDeviceKs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class TgCallBackKsIdServiceImpl extends ServiceImpl<TgCallBackKsIdMapper, TgCallBackKsId>
        implements TgCallBackKsIdService {
    @Autowired
    private RedisUtil redisUtil ;
    @Autowired
    private TgChannleService tgChannleService ;
    @Autowired
    private SysConfigService sysConfigService ;
    @Autowired
    private AppUserService appUserService ;
    @Autowired
    private TgChannleChildMapper tgChannleChildMapper ;
    @Autowired
    private TgBindCsjAdMapper tgBindCsjAdMapper ;
    @Override
    @Pooled(executor = "tgCallBackIdInp", poolOverAct = Pooled.PoolOverAct.NEW_THREAD)
    public void addTgCallBackKsId(String channle , TgDeviceKs tgDeviceKs) {
        if (StringUtils.isEmpty(tgDeviceKs.getCALLBACK()))return;
        if (StringUtils.isEmpty(channle))return;
        TgCallBackConf tgCallBackConf = tgChannleService.getTgCallBackConf(channle);
        if (tgCallBackConf == null){
            log.info("快手渠道"+channle+"未配置参数");
            return;
        }
        //回传类型  0 付费  1 广告ecpm
        Integer isCallbackType =tgCallBackConf.getCallbackType();
        //登录缓存时间（用于登录回传失效时间）
        Integer isCallbackLoginCacheTime =tgCallBackConf.getLoginCacheTime();
        TgCallBackKsId tgCallBackKsId = new TgCallBackKsId(channle , tgDeviceKs, isCallbackType);
        String IpMd5 = Md5Utils.getMD5(tgCallBackKsId.getChannelIp() , "utf8");
        String IpMd5Md5RES = RedisConstants.tgBackLoginLog_ks+IpMd5;
        String callbackparamCrc = RedisConstants.tgBackLoginLog_ks+tgCallBackKsId.getCallbackparamCrc();
        if (!redisUtil.hasKey(callbackparamCrc)){
            Integer count = count(new LambdaQueryWrapper<TgCallBackKsId>()
                    .eq(TgCallBackKsId::getCallbackparamCrc ,tgCallBackKsId.getCallbackparamCrc()));
            if (count<=0){
                save(tgCallBackKsId);
                redisUtil.setForObjectTimeCustom(callbackparamCrc, tgCallBackKsId, 5, TimeUnit.MINUTES);
                if (StringUtils.isNotEmpty(tgCallBackKsId.getChannelIp())){
                    redisUtil.setForObjectTimeCustom(IpMd5Md5RES, tgCallBackKsId, isCallbackLoginCacheTime, TimeUnit.HOURS);
                }
            }
        }
    }


    public static void main(String[] args) {
        System.out.println(Md5Utils.getMD5("171.214.202.251","UTF-8"));;
    }
   // https://bkservice.dyh2024.top/tg/ksCallback?type=2&IP=171.214.202.251&CID=7280328974&AID=397574783&ANDROIDID2=e4678ce50ef87110b12ae752b99c5d68&MODEL=&CALLBACK=http%3A%2F%2Fad.partner.gifshow.com%2Ftrack%2Factivate%3Fcallback%3DlguVoRut9JE4RyIH8weHKIpJjt3rH7ibIdM66jRx2UpzZTqMxu7MGaFEYZz98Iu69s2QGLJYeYaMLac8MEAznhBQbVkyo72P4jTAr2rHoFJPT5NQ2nqY0I_KsYZ-cLnUcn_Nd3DV8NOSaIWcRdmsxrExqDYwdrssmf_0UUqHYJdPwjKNxg3PfixeJVsqQXur5uy8is_X4-Y_Z1Zu6w_2AyFas6c58wK3s0FmxS_okPmW41IfIFjMf9chlcOs4k71XRzntJ32Zv1W77N6xvip9YvYwWQvDW9cPlt1vVT-6McRaFKgI2cAzvlisl42OkkR&DNAME=%E5%BA%94%E7%94%A8API%E8%BD%AC%E5%8C%96%E8%BF%BD%E8%B8%AA--%E8%AE%A1%E5%88%92%E6%A8%A1%E7%89%88&IDFA2=&MAC2=491774db6812c9325b7d9643d087d89c&UNITNAME=&UA=Mozilla%2F5.0+%28Linux%3B+Android+11%3B+Hebe-BD00+Build%2FHinovaHebe-BD00%3B+wv%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Version%2F4.0+Chrome%2F90.0.4430.226+KsWebView%2F1.8.90.597+%28rel%3Br%29+Mobile+Safari%2F537.36&OS=0&channle=ksaddiction-001&OAID2=9f89c84a559f573636a47ff8daed0d33&IMEI2=
    @Override
    public TgCallBackIdReids getTgCallBackKsId(Long userId, String ip, String key) {
        TgCallBackKsId tgCallBackKsId = null ;
        String modelIpMd5 = Md5Utils.getMD5(ip.replaceAll("\\s" , "") , "utf8");
        String modelIpMd5RES = key+modelIpMd5;
        TgCallBackIdReids tgCallBackIdReids = new TgCallBackIdReids();
        if (redisUtil.hasKey(modelIpMd5RES)){
            tgCallBackKsId = (TgCallBackKsId)redisUtil.getObejct(modelIpMd5RES);
            tgCallBackIdReids = new TgCallBackIdReids(tgCallBackKsId  , modelIpMd5  );
        }
        redisUtil.delete(modelIpMd5RES);
        return tgCallBackIdReids;
    }

    @Override
    public String ksCallBackLogin(Long userId , String ip) {
        TgCallBackIdReids tgCallBackIdReids =  getTgCallBackKsId(userId ,  ip,RedisConstants.tgBackLoginLog_ks);
        TgCallBackKsId tgCallBackKsId = tgCallBackIdReids.getTgCallBackKsId() ;
        String modelIpMd5 = tgCallBackIdReids.getModelIpMd5();
        if (tgCallBackKsId != null){
            TgCallBackConf tgCallBackConf = tgChannleService.getTgCallBackConf(tgCallBackKsId.getChannle());
            if (tgCallBackConf == null){
                log.info("快手渠道"+tgCallBackKsId.getChannle()+"未配置参数");
                return null;
            }
            //缓存时间（用于关键事件回传失效时间）
            Integer isCallbackEventCacheTime =tgCallBackConf.getEventCacheTime();
            //回传登录Key  active
            String loginKey =tgCallBackConf.getLoginKey();
            //是否回传关键事件
            Integer isCallBackEvent =tgCallBackConf.getIsCallBackEvent();

            tgCallBackKsId.setUserId(userId);
            //回传
            if (tgCallBackKsId.getIsCallbackType()==1){
                Boolean isDeduction = tgChannleService.isDeduction(tgCallBackKsId.getChannle() , null);
                if (isDeduction){
                    //不回传
                    tgCallBackKsId.setIsCallbackLogin(2);
                }else {
                    tgCallBackKsId.setIsCallbackLogin(1);
                    //回传
                    callBack(tgCallBackKsId ,loginKey );
                    if (isCallBackEvent == 1){
                        redisUtil.setForObjectTimeCustom(RedisConstants.tgBackAdLog_ks+userId, tgCallBackKsId, isCallbackEventCacheTime, TimeUnit.HOURS);
                    }
                }
            }else {
                tgCallBackKsId.setIsCallbackLogin(1);
                //回传
                callBack(tgCallBackKsId ,loginKey );
                if (isCallBackEvent == 1){
                    redisUtil.setForObjectTimeCustom(RedisConstants.tgBackPayLog_ks+modelIpMd5, tgCallBackKsId, isCallbackEventCacheTime, TimeUnit.HOURS);

                }
            }
            updateById(tgCallBackKsId);
            return tgCallBackKsId.getChannle();
        }else {
            log.info("快手渠道用户登录未匹配上：userID：" +userId);
            return null ;
        }
    }

    @Override
    public String ksCallBackPay(Long userId, String ip , Integer price) {
        TgCallBackIdReids tgCallBackIdReids = getTgCallBackKsId(userId ,  ip,RedisConstants.tgBackPayLog_ks);
        TgCallBackKsId tgCallBackKsId = tgCallBackIdReids.getTgCallBackKsId() ;
        if (tgCallBackKsId != null){
            TgCallBackConf tgCallBackConf = tgChannleService.getTgCallBackConf(tgCallBackKsId.getChannle());
            if (tgCallBackConf == null){
                log.info("快手渠道"+tgCallBackKsId.getChannle()+"未配置参数");
                return null;
            }
            //回传关键事件Key game_addiction
            String eventKey =tgCallBackConf.getEventKey();
            tgCallBackKsId.setUserId(userId);
            Boolean isDeduction = tgChannleService.isDeduction(tgCallBackKsId.getChannle() , price);
            if (isDeduction){
                //不回传
                tgCallBackKsId.setIsCallbackPay(2);
            }else {
                //回传
//                callBack(tgCallBackId ,"game_addiction" );
                callBack(tgCallBackKsId ,eventKey);
                tgCallBackKsId.setIsCallbackPay(1);
            }

            updateById(tgCallBackKsId);
            return tgCallBackKsId.getChannle();
        }else {
            return null ;
        }
    }






    public static void callBack(TgCallBackKsId tgCallBackKsId , String eventEype){
        String url = tgCallBackKsId.getCallback()+"&event_type="+eventEype+"&event_time="+new Date().getTime();
        String body = HttpUtil.doGet(url);
        log.info("快手联调 , 响应："+body + " callback: "+tgCallBackKsId.getCallback()+ " eventEype: "+eventEype);
    }

}

